package luo.handler;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.InvalidClaimException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import luo.Exception.LoginException;
import luo.utils.AjaxResult;
import luo.utils.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Author:let_free
 * @Date:2024/10/3/13:19
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(LoginException.class)
    public AjaxResult handleLoginException(LoginException e) {
        log.error("登录失败");
        return AjaxResult.error(e.getMessage());
    }


    @ExceptionHandler(ExpiredJwtException.class)
    public AjaxResult handleExpiredJwtException(ExpiredJwtException e) {
        log.error("token过期");
        return AjaxResult.error(HttpStatus.UNAUTHORIZED, "token过期");
    }

    @ExceptionHandler(InvalidClaimException.class)
    public AjaxResult handleInvalidClaimException(InvalidClaimException e) {
        log.error("token非法");
        return AjaxResult.error(HttpStatus.UNAUTHORIZED, "token非法");
    }

    @ExceptionHandler(JwtException.class)
    public AjaxResult handleJwtException(JwtException e, HttpServletRequest request) {
        log.error(request.getRequestURI()+"的请求token异常");
        return AjaxResult.error(HttpStatus.UNAUTHORIZED, e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e) {
        log.error("服务异常");
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(message);
    }
}
